package com.jh.paymentchannel.service;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.jh.paymentchannel.business.BranchbankBussiness;
import com.jh.paymentchannel.business.TopupPayChannelBusiness;
import com.jh.paymentchannel.pojo.BranchNo;
import com.jh.paymentchannel.pojo.JFQuickRegister;
import com.jh.paymentchannel.pojo.JFshangaoBindCard;
import com.jh.paymentchannel.util.Util;
import com.jh.paymentchannel.util.jifuquick.AES;
import com.jh.paymentchannel.util.jifuquick.Base64;
import com.jh.paymentchannel.util.jifuquick.HttpClient4Util;
import com.jh.paymentchannel.util.jifuquick.PayGetToken;
import com.jh.paymentchannel.util.jifuquick.TokenConstants;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Service
public class JFshangaoTopupRequest implements TopupRequest {

	private static final Logger log = LoggerFactory.getLogger(JFshangaoTopupRequest.class);

	@Autowired
	private TopupPayChannelBusiness topupPayChannelBusiness;

	@Autowired
	private BranchbankBussiness branchbankBussiness;

	@Autowired
	private Util util;

	@Value("${payment.ipAddress}")
	private String ipAddress;

	/*private static String partnerNo = "TEST001";

	private static String Key = "00000000000000000000000000000000";

	private String JFurl = "http://fast.jfpays.com:19087";*/
	
	@Value("${jfshangao.partnerNo}")
	private String partnerNo;
	
	@Value("${jfshangao.key}")
	private String Key;
	
	@Value("${jfshangao.url}")
	private String JFurl;

	private static final Charset UTF_8 = StandardCharsets.UTF_8;

	private String rateCode = "1001001";

	private String capAmount = "999999";

	@Override
	public Map<String, String> topupRequest(HttpServletRequest request, String amount, String ordercode,
			String orderdesc, String extra, String notifyurl, String returnurl, String channelParam) throws Exception {
		
		Map<String, String> map = new HashMap<String, String>();
		/** 首先拿到用户的userid, 如果用户已经存在，那么直接拿用户的sdjuserid, 如果用户的默认结算卡已经和当前不一样了。 需要重新注册 **/
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject;
		JSONObject resultObj;
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询订单信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有该订单信息");
			return map;
		}
		String realamount = resultObj.getString("realAmount");
		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");
		// 银行卡
		String bankCard = resultObj.getString("bankcard");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询默认结算卡有误");
			return map;
		}

		if (resultObj.isNullObject()) {

			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "没有结算卡");
			return map;
		}

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");
		// 开户行所在省
		String provinceOfBank = resultObj.getString("province");

		System.out.println("provinceOfBank" + provinceOfBank);
		// 开户行所在市
		String cityOfBank = resultObj.getString("city");

		System.out.println("cityOfBank" + cityOfBank);
		// 银行名称
		String bankName = resultObj.getString("bankName");
		// 支行名称
		String bankBranchName = resultObj.getString("bankBranchName");

		String cardType = resultObj.getString("cardType");

		String bankBranchNo;
		try {
			bankBranchNo = branchbankBussiness.getNumByName(bankBranchName);
		} catch (Exception e1) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询支行联行号有误");
			return map;
		}
		System.out.println("bankBranchNo" + bankBranchNo);

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/cardno";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("cardno", bankCard);
		requestEntity.add("type", "0");
		result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("接口/v1.0/user/bank/default/cardno--RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询银行卡信息出错");
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行卡信息有误");
			return map;
		}

		String cardName = resultObj.getString("bankName");
		String expiredTime = resultObj.getString("expiredTime");

		String securityCode = resultObj.getString("securityCode");

		String cardtype = resultObj.getString("cardType");

		String bankname = Util.queryBankNameByBranchName(bankName);
		String cardname = Util.queryBankNameByBranchName(cardName);

		// 根据银行名称查询得到银行信息
		BranchNo findByBankName;
		try {
			findByBankName = branchbankBussiness.findByBankName(bankname);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询银行信息有误");
			return map;
		}
		// 银行总行联行号
		String inBankUnitNo = findByBankName.getBankNo();

		JFQuickRegister jfQuickRegister;
		try {
			jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "查询用户进件信息有误");
			return map;
		}

		if (provinceOfBank == null || "".equals(provinceOfBank) || "null".equals(provinceOfBank)) {
			provinceOfBank = "";
		}

		if (cityOfBank == null || "".equals(cityOfBank) || "null".equals(cityOfBank)) {
			cityOfBank = "";
		}

		if (bankBranchNo == null || "".equals(bankBranchNo) || "".equals(bankBranchNo)) {
			bankBranchNo = "";
		}

		if (bankBranchName == null || "".equals(bankBranchName) || "null".equals(bankBranchName)) {
			bankBranchName = "";
		}

		if (expiredTime == null || "".equals(expiredTime) || "null".equals(expiredTime)) {
			expiredTime = "";
		}

		if (securityCode == null || "".equals(securityCode) || "null".equals(securityCode)) {
			securityCode = "";
		}

		if (jfQuickRegister == null) {
			log.info("用户需要进件========");
			// cjRegister为空表示用户需要进件
			Map maps = new HashMap();
			maps.put("resp_code", "success");
			maps.put("channel_type", "jf");
			maps.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
							+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
							+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
							+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
							+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
							+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
							+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=0");
			return maps;
		}

		JFshangaoBindCard jFshangaoBindCard = topupPayChannelBusiness.getJFshangaoBindCard(phone, bankCard);

		JFQuickRegister jfQuickRegisterByRateCode1 = topupPayChannelBusiness.getJFQuickRegisterByRateCode1(phone,
				rateCode);

		if(!rate.equals(jfQuickRegister.getDebitRate()) || !extraFee.equals(jfQuickRegister.getWithdrawDepositsingleFee())) {
			log.info("用户费率或者额外费用需要修改========");
			boolean updateRate = updateRate(ordercode);
			if(updateRate) {
				if(null == jfQuickRegisterByRateCode1) {
					log.info("商户费率编号需要新增========");
					boolean addJFQuickRateCode = addJFQuickRateCode(ordercode);
					if(addJFQuickRateCode) {
						
						if (jFshangaoBindCard == null) {
							log.info("用户需要绑卡========");
							map.put("resp_code", "success");
							map.put("channel_type", "jf");
							map.put("redirect_url",
									ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
											+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
											+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
											+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
											+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
											+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
											+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
											+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
											+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
							return map;
						} else if(!cardNo.equals(jfQuickRegister.getBankCard())){
							log.info("用户结算卡变更需要更改========");
							map.put("resp_code", "success");
							map.put("channel_type", "jf");
							map.put("redirect_url",
									ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
											+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
											+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
											+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
											+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
											+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
											+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
											+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
											+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
							return map;
						} else {
							log.info("发起交易========");
							map.put("resp_code", "success");
							map.put("channel_type", "jf");
							map.put("redirect_url",
									ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
											+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
											+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
											+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
											+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
											+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
											+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
											+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
											+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
							return map;
						}
						
					}else {
						map.put("resp_code", "failed");
						map.put("channel_type", "jf");
						map.put("resp_message", "亲，修改费率出错啦");
						return map;
					}
				}else {
					if (jFshangaoBindCard == null) {
						log.info("用户需要绑卡========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
						return map;
					} else if(!cardNo.equals(jfQuickRegister.getBankCard())){
						log.info("用户结算卡变更需要更改========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
						return map;
					} else {
						log.info("发起交易========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
						return map;
					}
				}
				
			}else {
				map.put("resp_code", "failed");
				map.put("channel_type", "jf");
				map.put("resp_message", "亲，修改费率出错啦");
				return map;
			}
		}else {
			
			if(null == jfQuickRegisterByRateCode1) {
				log.info("商户费率编号需要新增========");
				boolean addJFQuickRateCode = addJFQuickRateCode(ordercode);
				if(addJFQuickRateCode) {
					
					if (jFshangaoBindCard == null) {
						log.info("用户需要绑卡========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
						return map;
					} else if(!cardNo.equals(jfQuickRegister.getBankCard())){
						log.info("用户结算卡变更需要更改========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
						return map;
					} else {
						log.info("发起交易========");
						map.put("resp_code", "success");
						map.put("channel_type", "jf");
						map.put("redirect_url",
								ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
										+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
										+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
										+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
										+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
										+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
										+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
										+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
										+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
						return map;
					}
					
				}else {
					map.put("resp_code", "failed");
					map.put("channel_type", "jf");
					map.put("resp_message", "亲，修改费率出错啦");
					return map;
				}
			}else {
				if (jFshangaoBindCard == null) {
					log.info("用户需要绑卡========");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url",
							ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
									+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
									+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
									+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
									+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
									+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
									+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
									+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
									+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
					return map;
				} else if(!cardNo.equals(jfQuickRegister.getBankCard())){
					log.info("用户结算卡变更需要更改========");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url",
							ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
									+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
									+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
									+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
									+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
									+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
									+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
									+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
									+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
					return map;
				} else {
					log.info("发起交易========");
					map.put("resp_code", "success");
					map.put("channel_type", "jf");
					map.put("redirect_url",
							ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
									+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
									+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
									+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
									+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
									+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
									+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
									+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
									+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
					return map;
				}
			}
			
			
		}
		
		
		
		
		/*if (jFshangaoBindCard == null) {
			log.info("用户需要绑卡========");
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
							+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
							+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
							+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
							+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
							+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
							+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=1");
			return map;
		} else if(!cardNo.equals(jfQuickRegister.getBankCard())){
			log.info("用户结算卡变更需要更改========");
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
							+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
							+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
							+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
							+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
							+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
							+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=3");
			return map;
		} else {
			log.info("发起交易========");
			map.put("resp_code", "success");
			map.put("channel_type", "jf");
			map.put("redirect_url",
					ipAddress + "/v1.0/paymentchannel/topup/tojfshangaobankinfo?bankName="
							+ URLEncoder.encode(bankname, "UTF-8") + "&bankBranchId=" + bankBranchNo + "&bankNo="
							+ cardNo + "&bankCard=" + bankCard + "&cardName=" + URLEncoder.encode(cardname, "UTF-8")
							+ "&amount=" + amount + "&ordercode=" + ordercode + "&provinceOfBank="
							+ URLEncoder.encode(provinceOfBank, "UTF-8") + "&cityOfBank="
							+ URLEncoder.encode(cityOfBank, "UTF-8") + "&bankBranchName="
							+ URLEncoder.encode(bankBranchName, "UTF-8") + "&cardType="
							+ URLEncoder.encode(cardType, "UTF-8") + "&cardtype=" + URLEncoder.encode(cardtype, "UTF-8")
							+ "&expiredTime=" + expiredTime + "&securityCode=" + securityCode + "&isRegister=2");
			return map;
		}*/

	}

	// 修改费率
	public boolean updateRate(String ordercode) throws Exception {

		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		boolean istrue = false;
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");

		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
		}

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");

		// 修改进件信息接口的交易代码
		String txnCode = "701004";
		String api = "/rest/api/" + txnCode;

		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String merchantCode = jfQuickRegister.getMerchantCode();

		String CapAmount = new BigDecimal(capAmount).multiply(new BigDecimal("100")).setScale(0).toString();

		// 将额外费用变成以分为单位
		String ExtraFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.MERCHANT_CHANGE_TOKEN, ordercode, partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			return istrue;
		}

		JSONObject dto = new JSONObject();

		dto.put("token", token);// token
		dto.put("platMerchantCode", merchantCode);// 商户号
		dto.put("changeType", "1");// 交易费率变更
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("debitRate", rate);// 借记卡费率
		dto.put("debitCapAmount", CapAmount);// 借记卡封顶
		dto.put("creditRate", rate);// 信用卡费率
		dto.put("creditCapAmount", CapAmount);// 信用卡封顶
		dto.put("withdrawDepositSingleFee", ExtraFee);// 单笔提现手续费
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {

				jfQuickRegister.setDebitRate(rate);
				jfQuickRegister.setWithdrawDepositsingleFee(extraFee);

				topupPayChannelBusiness.createJFQuickRegister(jfQuickRegister);

				istrue = true;
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，修改费率失败啦！");

		}

		return istrue;

	}

	// 新增商户费率编号
	public boolean addJFQuickRateCode(String ordercode) throws Exception {

		Map map = new HashMap();
		Map<String, String> maps = new HashMap<String, String>();
		boolean istrue = false;
		RestTemplate restTemplate = new RestTemplate();
		URI uri = util.getServiceUrl("transactionclear", "error url request!");
		String url = uri.toString() + "/v1.0/transactionclear/payment/query/ordercode";
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("order_code", ordercode);
		String result = restTemplate.postForObject(url, requestEntity, String.class);
		log.info("RESULT================" + result);
		JSONObject jsonObject = JSONObject.fromObject(result);
		JSONObject resultObj = jsonObject.getJSONObject("result");

		String userid = resultObj.getString("userid");
		// 费率
		String rate = resultObj.getString("rate");
		// 额外费率
		String extraFee = resultObj.getString("extraFee");

		restTemplate = new RestTemplate();
		uri = util.getServiceUrl("user", "error url request!");
		url = uri.toString() + "/v1.0/user/bank/default/userid";
		requestEntity = new LinkedMultiValueMap<String, String>();
		requestEntity.add("user_id", userid);
		result = restTemplate.postForObject(url, requestEntity, String.class);

		log.info("RESULT================" + result);
		try {
			jsonObject = JSONObject.fromObject(result);
			resultObj = jsonObject.getJSONObject("result");
		} catch (Exception e) {
			log.error("查询默认结算卡出错");
		}

		String cardNo = resultObj.getString("cardNo");
		String userName = resultObj.getString("userName");
		/** 身份证号 */
		String idcard = resultObj.getString("idcard");
		String phone = resultObj.getString("phone");

		// 修改进件信息接口的交易代码
		String txnCode = "701004";
		String api = "/rest/api/" + txnCode;

		JFQuickRegister jfQuickRegister = topupPayChannelBusiness.getJFQuickRegisterByPhoneAndBankCard(phone, cardNo);
		String merchantCode = jfQuickRegister.getMerchantCode();

		String CapAmount = new BigDecimal(capAmount).multiply(new BigDecimal("100")).setScale(0).toString();

		// 将额外费用变成以分为单位
		String ExtraFee = new BigDecimal(extraFee).multiply(new BigDecimal("100")).setScale(0).toString();

		// 获取令牌
		String token = new PayGetToken().token(Key, TokenConstants.MERCHANT_CHANGE_TOKEN, ordercode, partnerNo, JFurl);

		if ("failed".equals(token)) {
			log.info("获取token出错啦=======");
			return istrue;
		}

		JSONObject dto = new JSONObject();

		dto.put("token", token);// token
		dto.put("platMerchantCode", merchantCode);// 商户号
		dto.put("changeType", "3");// 交易费率变更
		dto.put("rateCode", rateCode);// 费率编码
		dto.put("debitRate", rate);// 借记卡费率
		dto.put("debitCapAmount", CapAmount);// 借记卡封顶
		dto.put("creditRate", rate);// 信用卡费率
		dto.put("creditCapAmount", CapAmount);// 信用卡封顶
		dto.put("withdrawDepositSingleFee", ExtraFee);// 单笔提现手续费
		dto.put("head", this.getHead(ordercode, partnerNo, txnCode));

		// ordercode
		String execute = this.execute(Key, JFurl, api, dto.toString(), partnerNo, ordercode);
		log.info(execute);

		String res;
		// 返回状态码
		String respCode;
		String respMsg;
		try {
			com.alibaba.fastjson.JSONObject resJson = JSON.parseObject(execute);
			String sign = resJson.getString("signature");
			res = AES.decode(Base64.decode(resJson.getString("encryptData")), Key.substring(0, 16));

			jsonObject = JSONObject.fromObject(res);
			log.info("jsonObject=======" + jsonObject);
			JSONObject head = jsonObject.getJSONObject("head");
			respCode = head.getString("respCode");
			log.info("respCode=====" + respCode);
			respMsg = head.getString("respMsg");
			log.info("respMsg======" + respMsg);

			if ("000000".equals(respCode) && "success".equals(respMsg)) {

				jfQuickRegister.setRateCode1(rateCode);
				jfQuickRegister.setDebitRate(rate);
				jfQuickRegister.setWithdrawDepositsingleFee(extraFee);

				topupPayChannelBusiness.createJFQuickRegister(jfQuickRegister);

				istrue = true;
			}

		} catch (Exception e) {
			map.put("resp_code", "failed");
			map.put("channel_type", "jf");
			map.put("resp_message", "亲，新增商户编码失败啦！");

		}

		return istrue;

	}

	protected String execute(String key, String url, String api, String dataJson, String partnerNo, String orderId) {

		System.out.println("============ 请求报文:" + dataJson);
		String signKey = key.substring(16);
		String dataKey = key.substring(0, 16);
		String sign = DigestUtils.sha1Hex(dataJson + signKey);

		Map<String, String> params = Maps.newHashMap();
		params.put("encryptData", Base64.encode(AES.encode(dataJson, dataKey)));
		params.put("signData", sign);
		params.put("orderId", orderId);
		params.put("partnerNo", partnerNo);
		params.put("ext", "to be or not to be");

		System.out.println("encryptData : " + params.get("encryptData"));
		System.out.println("sign : " + params.get("sign"));
		System.out.println("partnerNo : " + params.get("partnerNo"));

		System.out.println("============ 请求地址:" + url + api);
		try {
			byte[] resByte = HttpClient4Util.getInstance().doPost(url + api, null, params);
			String resStr = new String(resByte, UTF_8);
			System.out.println("============ 返回报文原文:" + resStr);

			return resStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object getHead(String ordercode, String partnerNo, String txnCode) {
		JSONObject head = new JSONObject();
		head.put("version", "1.0.0");
		head.put("charset", "UTF-8");
		head.put("partnerNo", partnerNo); // 合作方标识号
		head.put("txnCode", txnCode); // 交易代码
		head.put("orderId", ordercode); // 订单号
		head.put("reqDate", DateTime.now().toString("yyyyMMdd"));
		head.put("reqTime", DateTime.now().toString("yyyyMMddHHmmss"));
		return head;
	}

}
